package com.yfp.client.service.impl.couponStrategy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.yfp.client.domain.dto.ClientCouponBestDTO;
import com.yfp.client.enums.CouponTypeEnum;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public abstract class AbstractClientCouponStrategy implements ClientCouponStrategy {

    @Override
    public ClientCouponBestDTO couponStrategy(BigDecimal priceOriginal, List<ClientCouponBestDTO> clientCoupons) {
        List<ClientCouponBestDTO> clientCouponDtoList = clientCoupons.stream().peek(item -> {
            if (CouponTypeEnum.BABY_CUSTOMER.getCode().equals(item.getType())) {
                item.setDiscountedAfterPrice(BigDecimal.ZERO);
                item.setDiscountMoney(priceOriginal);
                return;
            }
            item.setDiscountedAfterPrice(calculateDiscountedAfterPrice(priceOriginal, item));
            item.setDiscountMoney(calculateDiscountedPrice(priceOriginal, item));
        }).sorted(Comparator.comparing(ClientCouponBestDTO::getDiscountedAfterPrice).thenComparing(item -> {
            Date validEndTime = item.getValidEndTime();
            DateTime dateTime = DateUtil.offsetDay(validEndTime, item.getPostponeDay());
            return dateTime;
        })).limit(1).collect(Collectors.toList());

        return CollUtil.getFirst(clientCouponDtoList);
    }

    /**
     * 计算优惠后的金额
     * <p>
     * 10-2=8       计算后的值是8
     * 10*0.9=9     计算后的值是9
     *
     * @param priceOriginal
     * @param clientCoupons
     * @return
     */
    public abstract BigDecimal calculateDiscountedAfterPrice(BigDecimal priceOriginal, ClientCouponBestDTO clientCoupons);

    /**
     * 计算优惠了的金额
     * <p>
     * 10-2=8       计算后的值是2
     * 10*0.9=9     计算后的值是1
     *
     * @param priceOriginal
     * @param clientCoupons
     * @return
     */
    public abstract BigDecimal calculateDiscountedPrice(BigDecimal priceOriginal, ClientCouponBestDTO clientCoupons);
}
